package com.customization.unionpay.market.workflowaction;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.maketEnum.InstructionEnum;
import com.customization.unionpay.market.util.FormDataUtils;
import com.customization.unionpay.market.dao.MarketAdvanceCtrlDao;
import com.customization.unionpay.market.service.MarketAdvancePayWorkflowService;
import com.customization.unionpay.market.service.impl.MarketAdvancePayWorkflowServiceImpl;
import weaver.generalledger.action.ZzgdExecuteInstrucitonAction;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.OverTimeSetBean;
import weaver.workflow.request.RequestManager;

import java.util.List;
import java.util.Map;



/**
 * 营销预付款单同步至预算模块对活动预算授权码占用预算
 */
public class MarketAdvancePayAction  extends ZzgdExecuteInstrucitonAction implements Action {

    private static final Logger log = LoggerFactory.getLogger(MarketAdvancePayAction.class);

    @Override
    public String execute(RequestInfo requestInfo) {
        try {
            RequestManager rm = requestInfo.getRequestManager();
            OverTimeSetBean overTimeSetBean = new OverTimeSetBean();
            int nodeId = rm.getNodeid();
            String src = rm.getSrc();
            int formId = rm.getFormid();
            String loginid = rm.getUser().getLoginid();
            String tableName = rm.getBillTableName();
            int requestid = rm.getRequestid();

            MarketAdvancePayWorkflowService marketAdvancePayWorkflowService = new MarketAdvancePayWorkflowServiceImpl();
            List<JSONObject> list = marketAdvancePayWorkflowService.checkBudget("ZY", requestInfo);
            log.info("营销预付款预算调用占用list"+list);
//            List<JSONObject> releaseList = marketAdvancePayWorkflowService.checkBudget("SF", requestInfo);
//            log.info("营销预付款预算调用释放releaseList"+releaseList);
            Map<String, Object> mainTable = com.customization.unionpay.market.util.FormDataUtils.getMainFormData(requestInfo);
            List<Map<String, Object>> detailTable = com.customization.unionpay.market.util.FormDataUtils.getDetailFormDataByIndex(0, requestInfo);
            if (CollectionUtil.isEmpty(detailTable)) {
                log.error("明细表数据为空");
                return null;
            }
            // sfwdxy   是否为大协议
            String sfwdxy = mainTable.get("sfwdxy").toString();
            String sfwdxyName = FormDataUtils.getItemName(formId, "sfwdxy", sfwdxy);
//            BusinessBudgetServiceImpl businessBudgetService = new BusinessBudgetServiceImpl();
//            IContractBaseService contractBaseService = new ContractBaseServiceImpl();
//            Map<String, Object> otherMap = new HashMap<>();
//            Map<String, Object> params = new HashMap<>();
//            otherMap.put("logId", requestid);
//            otherMap.put("user", loginid);
            //如果流程是退回的
            if ("reject".equals(src)) {
                //调用预算释放
                if ("否".equals(sfwdxyName)) {
                    //todo 预算控制表释放预算

                    String instruction = com.customization.unionpay.market.maketEnum.InstructionEnum.SFZY.toString();
                    MarketAdvanceCtrlDao marketAdvanceCtrlDao = new MarketAdvanceCtrlDao();
                    for (JSONObject o : list) {
                        boolean result = marketAdvanceCtrlDao.insert(o, requestid, tableName);
                        if (!result) {
                            log.error("插入失败");
                            return Action.FAILURE_AND_CONTINUE;
                        }
                        }
                    log.info("数据已插入中间表");
                    ZzgdExecuteInstrucitonAction zzgdExecuteInstrucitonAction = new ZzgdExecuteInstrucitonAction();
                    zzgdExecuteInstrucitonAction.setZl(instruction);
                    String execute = zzgdExecuteInstrucitonAction.execute(requestInfo);
                    log.info(execute);
                    if("0".equals(execute)){
                        String messageid = requestInfo.getRequestManager().getMessageid();
                        log.info("messageid："+messageid);
                        String messagecontent = requestInfo.getRequestManager().getMessagecontent();
                        log.info("messagecontent："+messagecontent);
                        return Action.FAILURE_AND_CONTINUE;
                    }else {
                        log.info("预算释放占用调用成功！");
                    }
//                    params.put("params", releaseList);
//                    Map<String, Object> result = businessBudgetService.execBudget(params, otherMap);
//                    JSONArray arr = JSONArray.parseArray(result.get("result").toString());
//                    String status = arr.getJSONObject(0).getString("status");
//                    if ("0".equals(status)) {
//                        log.error("预算释放成功");
//                    } else if ("1".equals(status)) {
//                        log.error("预算释放失败");
//                    }
                }
            } else {
                //如果是发起
                String nodeName = overTimeSetBean.getNodeName(nodeId);
                String yfjehj = mainTable.get("yfjehj").toString();

                Integer lymxh = null;
                if ("发起".equals(nodeName)) {
                    if ("否".equals(sfwdxyName)) {
                        //预算占用
                        String instruction = InstructionEnum.ZY.toString();
                        MarketAdvanceCtrlDao marketAdvanceCtrlDao = new MarketAdvanceCtrlDao();
                        for (JSONObject o : list) {
                            boolean result = marketAdvanceCtrlDao.insert(o, requestid, tableName);
                            if (!result) {
                                log.error("插入失败");
                                return Action.FAILURE_AND_CONTINUE;
                            }
                        }
                        log.info("数据已插入中间表");
                        ZzgdExecuteInstrucitonAction zzgdExecuteInstrucitonAction = new ZzgdExecuteInstrucitonAction();
                        zzgdExecuteInstrucitonAction.setZl(instruction);
                        String execute = zzgdExecuteInstrucitonAction.execute(requestInfo);
                        log.info(execute);
                        if("0".equals(execute)){
                            String messageid = requestInfo.getRequestManager().getMessageid();
                            log.info("messageid："+messageid);
                            String messagecontent = requestInfo.getRequestManager().getMessagecontent();
                            log.info("messagecontent："+messagecontent);
                            return Action.FAILURE_AND_CONTINUE;
                        }else {
                            log.info("预算占用调用成功！");
                        }
//                        params.put("params", occupyList);
//                        Map<String, Object> verify = businessBudgetService.verify(params, otherMap);
//                        JSONArray arr = JSONArray.parseArray(verify.get("result").toString());
//                        String status = arr.getJSONObject(0).getString("status");
//                        String status="0";
//                        if (("0").equals(status)) {
//                            businessBudgetService.execBudget(params, otherMap);
//                        } else {
//                            return Action.FAILURE_AND_CONTINUE;
//                        }
//                        if ("submit".equals(src)) {
//                            for (Map<String, Object> detail : detailTable) {
//                                //获取明细表的履约明细号
//                                lymxh = Integer.valueOf(detail.get("lymxh").toString());
//                                //预付金额 写入合同台账【审批中金额】和【已占用合同计提金额】
//                                contractBaseService.updateJTZY(1, lymxh, yfjehj);
//                            }
//                        }

                    } else if ("结束".equals(nodeName)) {
//                        for (Map<String, Object> detail : detailTable) {
//                            lymxh = Integer.valueOf(detail.get("lymxh").toString());
//                            //【预付金额】写入合同明细行【已付款（含SQ申请）金额】，扣减【审批中金额】
//                            contractBaseService.updateJTZY(2, lymxh, yfjehj);
//                        }
                    } else {

                    }

                    return Action.SUCCESS;
                }
            }
        }catch (Exception e) {
            log.error("预付款单流程提交失败", e);
            return Action.FAILURE_AND_CONTINUE;
        }
        return Action.SUCCESS;
    }
}
